<template>
	<div style="height: 100%; background-color: #fff;">
		<div class="alert">
			<el-alert
				:title="'授权中...' + date"
				type="warning"
				:closable="false"
				center
				show-icon
				v-if="waitFor"
			>
			</el-alert>
			<el-alert
				title="授权成功"
				type="success"
				:closable="false"
				center
				show-icon
				v-if="success"
			>
			</el-alert>
			<el-alert
				title="授权超时，请重试"
				type="error"
				:closable="false"
				center
				show-icon
				v-if="overtime"
			>
			</el-alert>
		</div>
		<cl-crud ref="crud" @load="onLoad" :on-refresh="onRefresh">
			<el-row style="height: 100%" type="flex">
				<cl-biz-toolbar v-model="search.biz_id" @change="bizChange" />
				<cl-flex1 class="h-100" style="overflow: hidden">
					<cl-pagefull @resize="onResize">
						<template #head>
							<el-row type="flex">
								<div class="title">{{ biz_name }}</div>
								<cl-flex1 />
								<div>
									<cl-filter-group v-model="search" class="pr-1">
										<cl-filter label="所属事业部">
											<cl-select
												v-model="search.biz_id"
												placeholder="请选择"
												filterable
											>
												<el-option
													v-for="item in business"
													:key="item.biz_id"
													:label="item.biz_name"
													:value="item.biz_id"
												/>
											</cl-select>
										</cl-filter>
										<cl-filter label="品牌">
											<cl-select
												v-model="search.bra_id"
												placeholder="全部"
												clearable
												multiple
												collapse-tags
												filterable
											>
												<el-option
													v-for="item in bizRefData.brand"
													:key="item.bra_id"
													:label="item.bra_name"
													:value="item.bra_id"
												/>
											</cl-select>
										</cl-filter>
										<cl-filter label="账户/ID">
											<el-input
												v-model="search.keyword"
												placeholder="请输入账户名称 / ID"
												clearable
												style="width: 170px"
											/>
										</cl-filter>
										<!-- <cl-flex1 /> -->
									</cl-filter-group>
								</div>
								<div>
									<el-button
										icon="el-icon-plus"
										type="primary"
										@click="authorizedAccount"
									>
										授权媒体账户
									</el-button>
								</div>
							</el-row>
						</template>
						<div style="height: 95%">
							<cl-table v-bind="table" :columns="columnsList">
								<cl-empty slot="empty" />
								<template #header-user_name>
									<div style="text-align: center">推广人</div>
								</template>
								<template #header-account>
									<div style="text-align: center">账户信息</div>
								</template>
								<template #header-balance>
									<div style="text-align: center">余额</div>
								</template>
								<template #header-access_token_status>
									Token
									<el-tooltip placement="top">
										<span slot="content">如遇Token异常，请重新授权</span>
										<i class="el-icon-warning"></i>
									</el-tooltip>
								</template>
								<template #header-status>
									状态
									<el-tooltip placement="top">
										<span slot="content">如遇账户状态异常，请重新授权</span>
										<i class="el-icon-warning"></i>
									</el-tooltip>
								</template>
								<template #header-grab_status>
									是否采集
									<el-tooltip placement="top">
										<span slot="content">决定是否采集数据，如消耗、余额等</span>
										<i class="el-icon-warning"></i>
									</el-tooltip>
								</template>
								<template #header-xianfen_status>
									先锋计划
									<el-tooltip placement="top">
										<span slot="content">决定是否采集数据，如消耗、余额等</span>
										<i class="el-icon-warning"></i>
									</el-tooltip>
								</template>
								<template #column-account="{ scope: { row } }">
									<div class="ml20">{{ row.advertiser_name }}</div>
									<div class="ml20">id:{{ row.advertiser_id }}</div>
								</template>
								<template #column-access_token_status="{ scope: { row } }">
									<el-tag
										:type="row.access_token_status == 1 ? 'primary' : 'danger'"
									>
										{{ row.access_token_status == 1 ? "有效" : "无效" }}
									</el-tag>
								</template>
								<template #column-balance="{ scope: { row } }">
									<div class="ml20">
										{{ row.balance }}
										<el-tooltip placement="right">
											<div slot="content" class="tooltipBox">
												<div class="left">
													<span>总余额(元):{{ row.balance }}</span
													><br />
													<span>可用余额(元):{{ row.valid_balance }}</span
													><br />
													<span>现金余额(元):{{ row.cash }}</span
													><br />
													<span>现金可用(元):{{ row.valid_cash }}</span>
												</div>
												<div class="right">
													<span>赠款余额(元):{{ row.grants }}</span
													><br />
													<span>赠款可用(元):{{ row.valid_grant }}</span>
												</div>
											</div>
											<i class="el-icon-warning"></i>
										</el-tooltip>
									</div>
									<div class="ml20">更新时间:{{ row.fund_time }}</div>
								</template>
								<template #column-status="{ scope: { row } }">
									<el-tag :type="row.status == 1 ? 'primary' : 'danger'">
										{{ row.status == 1 ? "正常" : "异常" }}
									</el-tag>
								</template>
								<template #column-xianfen_status="{ scope: { row } }">
									<el-switch
										v-model="row.xianfen_status"
										:active-value="1"
										:inactive-value="2"
										@change="xianfengChange(row)"
									/>
								</template>
								<template #column-opt="{ scope: { row } }">
									<el-button type="primary" @click="getChildList(row)">
										子账户
									</el-button>
									<el-button
										type="warning"
										@click="Reauthorize(row)"
										:disabled="waitFor"
									>
										重新授权
									</el-button>
									<el-button type="danger" @click="goExternalWebsite">
										取消授权
									</el-button>
								</template>
							</cl-table>
						</div>
					</cl-pagefull>
				</cl-flex1>
			</el-row>
			<!-- 新增授权账户 -->
			<authorized-account-form ref="authorizedAccountFormRef" @refresh="refresh" />
			<media-account-child ref="mediaAccountChildRef" @refresh="refresh" />
			<binding-distributor-form ref="bindingDistributorFormRef" @refresh="refresh" />
		</cl-crud>
	</div>
</template>

<script>
import { mapGetters } from "vuex";
import authorizedAccountForm from "./components/authorized-account-form";
import mediaAccountChild from "./components/media-account-child";
import bindingDistributorForm from "./components/binding-distributor-form";
import axios from "axios";
import dayjs from "dayjs";
// import Json from "archiver/lib/plugins/json";
export default {
	name: "SetPromotionmediaAccount",
	components: {
		authorizedAccountForm,
		mediaAccountChild,
		bindingDistributorForm
	},
	data() {
		return {
			search: {
				bra_id: [],
				keyword: "",
				biz_id: ""
			},
			biz_name: "",
			table: {
				"context-menu": ["refresh"],
				props: {
					maxHeight: 500
				}
			},
			// load: false,
			requestTimer: null,
			num: 0, //授权请求次数
			waitFor: false,
			success: false,
			overtime: false,
			date: dayjs().format("YYYY-MM-DD HH:mm:ss")
		};
	},
	computed: {
		bizRefData() {
			const { biz_id } = this.search;
			return this.getBizRefData(biz_id);
		},
		columnsList() {
			const list = [
				{
					label: "所属品牌",
					prop: "bra_name",
					minWidth: 150,
					showOverflowTooltip: true
				},
				{
					label: "账户信息",
					prop: "account",
					minWidth: 150,
					align: "left",
					showOverflowTooltip: true
				},
				{ label: "余额", prop: "balance", width: 220, align: "left" },
				{ label: "绑定广告账户", prop: "advertiser_id", minWidth: 120 },
				{ label: "推广人", prop: "user_name", minWidth: 220 },
				{ label: "Token", prop: "access_token_status", width: 150 },
				{ label: "状态", prop: "status", width: 150 },
				{ label: "授权应用", prop: "app_name", minWidth: 120 },
				{ label: "是否采集", prop: "grab_status", width: 100 },
				{ label: "先锋计划", prop: "xianfen_status", width: 100 },
				{
					label: "操作",
					prop: "opt",
					width: 280,
					fixed: "right",
					disable: true
				}
			];
			return list.filter(
				e =>
					!["grab_status", "xianfen_status", "advertiser_id", "user_name"].includes(
						e.prop
					)
			);
		},
		...mapGetters(["browser"])
	},
	methods: {
		async init() {
			const { biz_id } = this.search;
			this.getBizRefBrand(biz_id);
		},
		onLoad({ ctx, app }) {
			ctx.service(this.$service.media)
				.set("dict", {
					api: {
						page: "accountList"
					}
				})
				.done();
			// if (!this.load) return;
			app.refresh();
		},
		async onRefresh(params, { next, done, render }) {
			const { biz_id } = this.search;
			console.log(biz_id);
			let data = await next({
				...params,
				biz_id
			});
			render(data);
		},
		//切换左侧事业部
		bizChange(v) {
			this.search.biz_id = v.biz_id;
			this.biz_name = v.biz_name;
			this.search.bra_id = [];
			this.init();
			this.refresh();
		},
		//绑定广告账户
		distributor(row) {
			this.$refs.bindingDistributorFormRef.open(row);
		},
		//授权媒体账户
		authorizedAccount(row) {
			let { type, biz_id } = this.search;
			setTimeout(() => {
				this.$refs.authorizedAccountFormRef.open(type, biz_id);
			}, 300);
		},
		//先锋计划开关的状态
		async xianfengChange(row) {
			console.log(row);
			if (row.xianfen_status === 2) {
				let res = await axios.get("https://adxh.xmzmmr.com/Auth/removeXianfen", {
					params: { id: row.id }
				});
				console.log(res);
				if (res.data.code === 200) {
					this.$message.success("操作成功");
				} else {
					this.$message.warning("操作失败，请重试");
				}
			} else {
				let res = await axios.get("https://adxh.xmzmmr.com/Auth/recoveryXianfen", {
					params: { id: row.id }
				});
				console.log(res);
				if (res.data.code === 200) {
					this.$message.success("操作成功");
				} else {
					this.$message.warning("操作失败，请重试");
				}
			}
			this.refresh(_, false);
		},
		//打开子级列表抽屉
		getChildList(row) {
			this.$refs.mediaAccountChildRef.open(row);
		},
		//取消授权
		goExternalWebsite() {
			window.open(
				"https://ad.oceanengine.com/webstore/audit/list.html?rid=m0p7iunzmii",
				"_blank"
			);
		},
		//授权
		async Reauthorize(row) {
			const data = await this.$service.accountManage
				.oauthUrl({ id: row.app_id })
				.catch(err => {
					this.$message.warning("授权失败，请重试");
				});

			window.open(data, "_blank");

			return false
			this.num = 0;
			let res = await axios.get("https://adxh.xmzmmr.com/Auth/url", {
				params: { id: row.app_id }
			});
			console.log(res);
			if (res.data.code === 200) {
				if (!res.data.result.code) {
					let state = res.data.result.state;
					window.open(res.data.result.url, "_blank");
					this.waitFor = true;
					setTimeout(() => {
						this.requestTimer = setInterval(async () => {
							let result = await axios.get(
								"https://adxh.xmzmmr.com/Auth/urlCallback",
								{
									params: {
										state
									}
								}
							);
							if (!result.data.result.code) {
								clearInterval(this.requestTimer);
								this.$message.closeAll();
								this.waitFor = false;
								this.success = true;
								setTimeout(() => {
									this.success = false;
								}, 3000);
							} else {
								this.num += 2;
								this.date = dayjs().format("YYYY-MM-DD HH:mm:ss");
								if (this.num > 40) {
									clearInterval(this.requestTimer);
									this.requestTimer = null;
									this.$message.closeAll();
									this.waitFor = false;
									this.overtime = true;
									setTimeout(() => {
										this.overtime = false;
									}, 2000);
								}
							}
						}, 2000);
					}, 5000);
				} else {
					this.$message.warning("授权还未过期，无需重新授权");
				}
			} else {
				this.$message.warning("授权失败，请重试");
			}
		},
		// crud刷新
		refresh(biz_id, reset = true) {
			let params = { ...this.search };
			if (reset) {
				params.page = 1;
			}
			clearInterval(this.requestTimer);
			this.$refs.crud.refresh(params);
			// this.load = true;
		},
		onResize(h) {
			console.log(h);
			this.table.props.maxHeight = h * 0.9;
		}
	}
};
</script>

<style lang="scss" scoped>
.ml20 {
	margin-left: 20px;
}

.title {
	font-size: 18px;
}

.tooltipBox {
	display: flex;
	// box-sizing: border-box;
	// width: 260px;
	line-height: 20px;
	white-space: nowrap;

	.left {
		width: 50%;
	}

	.right {
		margin-left: 30px;
		width: 50%;
	}
}

.alert {
	position: absolute;
	width: 300px;
	height: 20px;
	top: 7px;
	left: 0;
	right: 0;
	margin: 0 auto;
	z-index: 10;
}
</style>
